//
//  CountDownView.swift
//  Pomodoro
//
//  Created by zhengju on 2018/3/1.
//  Copyright © 2018年 zhengju. All rights reserved.
//

import UIKit

class CountDownView: UIView {
    var timeCountLabel: UILabel!
    var timeCount :Int = Int(0.1*60)
    var codeTimer :DispatchSource!
    var timeLabel :UILabel!
    
    var startBtn :UIButton!
    var finishBtn :UIButton!
    
    var timerComplete:(()->())!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.gray
        initUI()
        initTimer()
    }
    
    /// 初始化定时器
    func initTimer() {
        
        codeTimer  = DispatchSource.makeTimerSource(queue:DispatchQueue.global()) as! DispatchSource
        
        codeTimer.schedule(deadline: .now(), repeating: .seconds(1))

        codeTimer.setEventHandler {[weak self] in
            //每一秒一次
  
            self?.timeCount = (self?.timeCount)! - 1
                
            if (self?.timeCount)! <= 0{
                self?.codeTimer.cancel()
                    
                }
                //在主线程中刷新
                DispatchQueue.main.async {
                    self?.timeLabel.text = self?.timeFormatted(totalSeconds: (self?.timeCount)!)
                }

        }
        codeTimer.setCancelHandler {[weak self] in

                if (self?.timerComplete != nil){
                    self?.timerComplete()
                }
        }
        codeTimer.resume()
    }
    
    /// Int转时间(分秒)
    ///
    /// - Parameter totalSeconds: Int秒数
    /// - Returns: 时间字符串
    func timeFormatted(totalSeconds:Int) -> String {
        let  seconds = totalSeconds % 60;
        let  minutes = (totalSeconds / 60) % 60;
        return (minutes > 9 ? String(minutes) : ("0" + String(minutes))) + ":" + (seconds > 9 ? String(seconds) : ("0" + String(seconds)))
    }
    
    /// 初始化UI
    func initUI() {
        
        
        timeCountLabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: 60, height: 30))
        timeCountLabel.font = UIFont.systemFont(ofSize: 17)
        timeCountLabel.textAlignment = .center
        timeCountLabel.textColor = UIColor.white
        self.addSubview(timeCountLabel)
        self.addSubview(timeCountLabel)
        let timeString = timeFormatted(totalSeconds: timeCount)
        let first = timeString.components(separatedBy: ":").first
        timeCountLabel.text = first
        
        
        
        timeLabel = UILabel.init(frame: CGRect.init(x: 0, y: 100, width: self.bounds.size.width, height: 200))
        timeLabel.font = UIFont.systemFont(ofSize: 100)
        timeLabel.textAlignment = .center
        timeLabel.textColor = UIColor.white
        self.addSubview(timeLabel)
        
        
        let btnWidth = 80.00
        let spacing = (Double(SCREEN_WIDTH) - 2*btnWidth )/3.0
        
        startBtn = UIButton.init(frame: CGRect.init(x: spacing, y: 350, width: btnWidth, height: btnWidth))
        startBtn.backgroundColor = UIColor.red
        startBtn.setTitle("休息", for: .normal)
        startBtn.setTitleColor(UIColor.white, for: .normal)
        startBtn.addTarget(self, action: #selector(finishAction), for: .touchUpInside)
        self.addSubview(startBtn)
        
        finishBtn = UIButton.init(frame: CGRect.init(x: Double(SCREEN_WIDTH) - btnWidth - spacing , y: 350, width: btnWidth, height: btnWidth))
        finishBtn.backgroundColor = UIColor.red
        finishBtn.setTitle("专注", for: .normal)
        finishBtn.setTitleColor(UIColor.white, for: .normal)
        finishBtn.addTarget(self, action: #selector(startAction), for: .touchUpInside)
        self.addSubview(finishBtn)
        
    }
    
    @objc func startAction() {
   
        
        if timeCount <= 0 {
            timeCount = 10
            initTimer()
            return;
        }
        
        codeTimer.resume()

    }
    @objc func finishAction() {
        codeTimer.suspend()
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
